import { useAtom } from 'jotai'
import { assistantListAtom } from '@/atoms'
import { Assistant } from '@/types'
import { v7 as uuidv7 } from 'uuid'
import { showEditAssistantDialog } from '@/components/Dialogs/AssistantEdit'
import { showAlertDialog } from '@/components/Base/Alert'

export default function useAssistant() {
  const [assistants, setAssistants] = useAtom(assistantListAtom)

  const saveAssistants = (detail: Assistant) => {
    const id = detail.id
    const findIndex = assistants.findIndex(item => item.id == id)
    if (findIndex >= 0) {
      assistants.splice(findIndex, 1, detail)
      setAssistants([...assistants])
    }
    else {
      setAssistants((assistants: Assistant[]) => {
        return [...assistants, detail]
      })
    }
  }

  const deleteAssistant = (id: string) => {
    setAssistants(assistants.filter(item => item.id != id))
  }

  const copyAssistant = (id: string) => {
    const assistant = assistants.find(item => item.id == id)
    if (assistant) {
      setAssistants([...assistants, { ...assistant, id: uuidv7() }])
    }
  }

  const alertChooseAssistant = () => {
    showAlertDialog({
      title: 'assistant alert title',
      content: 'assistant alert message',
      onOk: () => {
        if (assistants.length <= 0) {
          showEditAssistantDialog()
        }
      },
    })
  }

  return {
    saveAssistants,
    deleteAssistant,
    copyAssistant,
    alertChooseAssistant,
  }
}
